package org.university.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.university.common.ApiResponse;
import org.university.dto.response.CourseResponseDTO;
import org.university.entity.Course;
import org.university.exception.ResourceNotFoundException;
import org.university.repository.EnrollmentRepository;
import org.university.service.CourseService;
import org.university.service.impl.CourseServiceImpl;

import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/courses")
public class CourseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CourseController.class);
    private final CourseService courseService;
    private final CourseServiceImpl courseServiceImpl;
    private final EnrollmentRepository enrollmentRepository;

    public CourseController(CourseService courseService, CourseServiceImpl courseServiceImpl, EnrollmentRepository enrollmentRepository) {
        this.courseService = courseService;
        this.courseServiceImpl = courseServiceImpl;
        this.enrollmentRepository = enrollmentRepository;
    }

    /**
     * 获取课程信息分页
     *
     * @param page 页码
     * @param size 页面大小
     * @return 信息分页
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<Course>>> getCourse(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        // LOGGER.info("查询课程：页码={}, 每页大小={}", page, size);
        Page<Course> courses = courseService.findAll(PageRequest.of(page, size));
        return ApiResponse.success(courses);
    }

    @GetMapping("/getSelectedCourses/{id}")
    public ResponseEntity<ApiResponse<List<CourseResponseDTO>>> getSelectedCoursesByStudentId(
            @PathVariable String id
    ) {
        List<Course> c = enrollmentRepository.findCoursesByStudentId(id);
        List<CourseResponseDTO> list = new ArrayList<>();
        for (Course c1 : c) {
            CourseResponseDTO dto = new CourseResponseDTO();
            dto.setCourseId(c1.getCourseId());
            dto.setCourseName(c1.getCourseName());
            dto.setCourseType(c1.getCourseType());
            dto.setHours(c1.getHours());
            dto.setCredit(c1.getCredit());
            list.add(dto);
        }
        return ApiResponse.success(list);
    }

    /**
     * 根据ID查找课程
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Course>> getCourseById(@PathVariable String id) {
        LOGGER.info("查询课程ID: {}", id);
        return courseService.findById(id)
                .map(ApiResponse::success)
                .orElseThrow(() -> new ResourceNotFoundException("未找到id为：" + id + " 的课程"));
    }

    /**
     * 创建课程
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Course>> createCourse(@RequestBody Course course) {
        LOGGER.info("创建课程ID: {}", course.getCourseId());
        Course newCourse = courseService.save(course);
        return ApiResponse.created(newCourse);
    }

    /**
     * 更新课程信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<CourseResponseDTO>> updateCourse(
            @PathVariable String id,
            @RequestBody Course updateCourse) {

        LOGGER.info("更新课程ID: {}", id);
        if (courseService.findById(id).isEmpty()) {
            return ApiResponse.error(HttpStatus.NOT_FOUND, "未找到id为：" + id + " 的课程");
        }

        /*
        // 逻辑没问题，但不生效
        // 保存新课程
        courseServiceImpl.update(id, updateCourse);
        */

        // 新建一个课程，替换需要更新的字段
        Course course = new Course();
        course.setCourseId(updateCourse.getCourseId());
        course.setCourseName(updateCourse.getCourseName());
        course.setCourseType(updateCourse.getCourseType());
        course.setHours(updateCourse.getHours());
        course.setCredit(updateCourse.getCredit());
        course.setDescription(updateCourse.getDescription());

        // 删除旧课程
        courseService.deleteById(id);
        // 保存新课程
        courseService.save(course);

        // 构建返回体
        CourseResponseDTO responseDTO = new CourseResponseDTO();
        responseDTO.setCourseId(updateCourse.getCourseId());
        responseDTO.setCourseName(updateCourse.getCourseName());
        responseDTO.setCourseType(updateCourse.getCourseType());
        responseDTO.setHours(updateCourse.getHours());
        responseDTO.setCredit(updateCourse.getCredit());
        responseDTO.setDescription(updateCourse.getDescription());

        return ApiResponse.success(responseDTO);
    }

    /**
     * 删除课程
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteCourse(@PathVariable String id) {
        LOGGER.info("删除课程ID: {}", id);
        if (courseService.findById(id).isEmpty()) {
            return ApiResponse.error(HttpStatus.NOT_FOUND, "未找到id为：" + id + " 的课程");
        }
        courseService.deleteById(id);
        return ResponseEntity.ok().build();
    }
}
